/**
 * Copyright (C) 2018-2020
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package co.yixiang.modules.statistics.rest;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import co.yixiang.api.ApiResult;
import co.yixiang.api.YshopException;
import co.yixiang.common.aop.NoRepeatSubmit;
import co.yixiang.common.bean.LocalUser;
import co.yixiang.common.interceptor.AuthCheck;
import co.yixiang.enums.*;
import co.yixiang.modules.auction.service.YxAuctionOrderService;
import co.yixiang.modules.auction.service.YxAuctionRecordService;
import co.yixiang.modules.auction.service.dto.YxAuctionOrderList;
import co.yixiang.modules.auction.service.dto.YxAuctionRecordDto;
import co.yixiang.modules.commom.domain.YxAppdict;
import co.yixiang.modules.commom.service.YxAppdictService;
import co.yixiang.modules.news.domain.YxNews;
import co.yixiang.modules.news.domain.YxUserNews;
import co.yixiang.modules.news.service.YxNewsService;
import co.yixiang.modules.news.service.YxUserNewsService;
import co.yixiang.modules.order.domain.YxStoreOrder;
import co.yixiang.modules.order.domain.YxStoreOrderCartInfo;
import co.yixiang.modules.order.dto.OrderExtendDto;
import co.yixiang.modules.order.dto.OrderResDto;
import co.yixiang.modules.order.param.*;
import co.yixiang.modules.order.service.YxStoreOrderCartInfoService;
import co.yixiang.modules.order.service.YxStoreOrderService;
import co.yixiang.modules.order.service.YxStoreOrderStatusService;
import co.yixiang.modules.order.vo.ComputeVo;
import co.yixiang.modules.order.vo.ConfirmOrderVo;
import co.yixiang.modules.order.vo.OrderCartInfoVo;
import co.yixiang.modules.order.vo.YxStoreOrderQueryVo;
import co.yixiang.modules.pay.AppPayService;
import co.yixiang.modules.product.service.YxStoreProductService;
import co.yixiang.modules.services.CreatShareProductService;
import co.yixiang.modules.services.OrderSupplyService;
import co.yixiang.modules.statistics.dto.Statistics;
import co.yixiang.modules.statistics.dto.YxUserDto;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.domain.YxUserAddress;
import co.yixiang.modules.user.domain.YxUserBill;
import co.yixiang.modules.user.domain.YxUserinfo;
import co.yixiang.modules.user.service.YxUserAddressService;
import co.yixiang.modules.user.service.YxUserBillService;
import co.yixiang.modules.user.service.YxUserService;
import co.yixiang.modules.user.service.YxUserinfoService;
import co.yixiang.modules.user.service.dto.FansListDto;
import co.yixiang.modules.user.service.mapper.YxDistributorRelationMapper;
import co.yixiang.tools.express.ExpressService;
import co.yixiang.tools.express.config.ExpressAutoConfiguration;
import co.yixiang.tools.express.dao.ExpressInfo;
import co.yixiang.utils.FileUtil;
import co.yixiang.utils.RandonOrderNoUtil;
import co.yixiang.utils.RedisUtils;
import co.yixiang.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 订单控制器
 * </p>
 *
 * @author hupeng
 * @since 2019-10-27
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "统计模块", tags = "统计下级数据", description = "统计模块")
public class StatisticsController {


    @Autowired
    private final YxDistributorRelationMapper distributorRelationMapper;

    private final YxAuctionOrderService yxAuctionOrderService;

    private final YxAuctionRecordService yxAuctionRecordService;
    private final YxUserService userService;

    @Autowired
    private YxUserAddressService yxUserAddressService;

    @PostMapping("/excl")
    @ApiOperation(value = "excl",notes = "excl")
    public void excl( HttpServletResponse response) throws IOException {
        List<YxUserAddress> list1 = yxUserAddressService.list();
        List<Map<String, Object>> list = new ArrayList<>();
        for (YxUserAddress address : list1) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户名", address.getRealName());
            map.put("手机号码", address.getPhone());
            map.put("省", address.getProvince());
            map.put("市", address.getCity());
            map.put("区", address.getDistrict());
            map.put("详细地址", address.getDetail());
            list.add(map);
        }
//        FileUtil.downloadExcel(list, response);
//        List employees = new ArrayList<>();
//        for (int i = 0; i < 10; i++) {
//            employees.add(list1.get(i));
//        }

        ExcelWriter writer = ExcelUtil.getWriter();
        writer.addHeaderAlias("name", "姓名");
        writer.addHeaderAlias("age", "年龄");
       // writer.merge(1, "用户地址");
        writer.write(list, true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");

        String name =("XXX国际贸易公司");

        response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xls");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
        IoUtil.close(out);
    }




    /**
     * 订单确认
     */
  //  @AuthCheck
    @PostMapping("/statistics")
    @ApiOperation(value = "下级用户数据列表",notes = "下级用户数据列表")
    public ApiResult<IPage> statistics(@RequestParam(value = "referralCode" ) String  referralCode,
                                           @RequestParam(value = "page" ,defaultValue = "1") Integer page,
                                           @RequestParam(value = "limit" ,defaultValue = "10") Integer limit){
       // YxUser user = LocalUser.getUser();
        //查询该用户的下级
        Page<YxUser> pageModel = new Page<>(page, limit);
        QueryWrapper    queryWrapper=new QueryWrapper();
        queryWrapper.eq("referral_code",referralCode);
        IPage<YxUserDto> page1 = userService.page(pageModel, queryWrapper);

        return ApiResult.ok(page1);
    }
    /**
     * 订单确认
     */
   // @AuthCheck
    @PostMapping("/confirm")
    @ApiOperation(value = "下级总用户数据统计",notes = "下级总用户数据统计")
    public ApiResult<Map> confirm( String  referralCode){
       // YxUser yxUser = LocalUser.getUser();
        Map map1=new HashMap();

        QueryWrapper    queryWrapper=new QueryWrapper();
        queryWrapper.select("IFNULL(sum(now_money),0) as allmoney")
                .eq("referral_code",referralCode);
        Map<String, Object> map = userService.getMap(queryWrapper);
        BigDecimal allmoney = (BigDecimal) map.get("allmoney");
        QueryWrapper    queryWrapper1=new QueryWrapper();
        queryWrapper1.select("IFNULL(sum(brokerage_price),0) as allbrokerage")
                .eq("referral_code",referralCode);
        Map<String, Object> map2 = userService.getMap(queryWrapper1);
        BigDecimal allbrokerage = (BigDecimal) map2.get("allbrokerage");
        map1.put("allprice",allmoney);
        map1.put("allbrokerage",allbrokerage);
        return ApiResult.ok(map1);

    }
    /**
     * 我的卖单列表
     * 1等待转拍2转拍中3待确定4转拍完成
     */
   // @AuthCheck
    @GetMapping("/order")
    @ApiOperation(value = "卖单列表", notes = "卖单列表")
    public ApiResult<Page<YxAuctionRecordDto>> order(@PathVariable Long uid ,
                                                         @RequestParam(value = "page",defaultValue = "1") int page,
                                                         @RequestParam(value = "limit",defaultValue = "10") int limit){
     //   YxUser yxUser = LocalUser.getUser();

        return ApiResult.ok(yxAuctionRecordService.orderPage(uid,4,page,limit));
    }


   // @AuthCheck
    @GetMapping("/productOrder")
    @ApiOperation(value = "买单列表", notes = "买单列表")
    public ApiResult<Page<YxAuctionOrderList>> product(@PathVariable Long uid,
                                                                @RequestParam(value = "page",defaultValue = "1") int page,
                                                                @RequestParam(value = "limit",defaultValue = "10") int limit){

       // YxUser yxUser=LocalUser.getUser();
        return  yxAuctionOrderService.productOrderPage(uid,4,page,limit);
    }

}

